import type Dish from '@/types/entity/Dish'
import type { DishFlavor } from '@/types/entity/DishFlavor'

// 选择的口味
export class Flavor {
  // 口味id
  id: number
  // 口味名
  name: string
  // 增值
  appreciation: number
  public static parse(flavorAndAppreciation: string): FlavorNameObj {
    // flavorAndAppreciation的值例如“加饭:+1”
    const [name, appreciation] = flavorAndAppreciation.split(/[:：]/)
    return { name, appreciation: parseFloat(appreciation ?? 0) ?? 0 }
  }
}
// 口味名对象
export class FlavorNameObj {
  name: string
  appreciation?: number
  public static getMinimumPriceFlavor(flavorNamesStr: string): { name: string; price: number } | null {
    // 传入口味值得到价格最低的那个值（口味名，价格）
    if (flavorNamesStr == null || flavorNamesStr === '') return null
    const flavorAndAppreciations = flavorNamesStr.split(',')
    let result: { name: string; price: number } | null = null
    for (const flavorAndAppreciation of flavorAndAppreciations) {
      const { name, appreciation } = Flavor.parse(flavorAndAppreciation)
      if (result == null || appreciation! < result.price) {
        result = {
          name: name,
          price: appreciation!
        }
      }
    }
    return result
  }
  public static getDishMinimumAppreciationSum(flavors: DishFlavor[]) {
    if (flavors == null || flavors.length === 0) return 0
    let minimumAppreciationSum = 0
    flavors.forEach((flavor) => {
      minimumAppreciationSum += FlavorNameObj.getMinimumPriceFlavor(flavor.value)?.price ?? 0
    })
    return minimumAppreciationSum
  }
}
// 前端操作数据，在购物车中的菜品项
export class CartItem {
  /** 菜品分类id */
  dishCategoryId: number
  // 后端返回的规格key
  dishSpecificationKey?: string
  // 店铺id
  shopId?: number
  // 邀请码
  inviteCode?: string
  // 座位码
  seatNumber?: string
  // 菜品id
  id: number
  // 选择的口味
  flavors?: Flavor[]
  // 数量
  count: number
  // 菜品结合口味后的价格
  price: number

  // 获取规格描述
  public static genSpecificationsDesc(flavors: Flavor[] | undefined): string {
    let content = ''
    if (flavors == null || flavors.length === 0) return content
    for (const [index, flavor] of flavors.entries()) {
      content += `${index === 0 ? '' : ','}${flavor.name}`
    }
    return content
  }
}
